/*******************************************************************************
 * Copyright (c) 2014 Francesco Gabbrielli.
 * 
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     Francesco Gabbrielli - initial API and implementation
 ******************************************************************************/
package it.francescogabbrielli.android.solidalapp;

import it.francescogabbrielli.android.solidalapp.SolidalApp.DataKey;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import android.util.Log;

/**
 * Implement get address api (reverse lookup) to auto-fill details
 */
public class GetAddressTask extends AsyncTask<Location, Void, String> {
	
	private BaseActivity context;
		
	public GetAddressTask(BaseActivity context) {
	    super();
	    this.context = context;
	}
	
	@Override
	protected String doInBackground(Location... params) {
		Log.d(SolidalApp.TAG, "Location: "+params[0]);
        Location loc = params[0];
        if(loc==null || context==null)
        	return "";
		Geocoder geocoder = new Geocoder(context, Locale.getDefault());
        List<Address> addresses = null;
        try {
            addresses = geocoder.getFromLocation(loc.getLatitude(),
                    loc.getLongitude(), 1);
        } catch (IOException e1) {
            Log.e("LocationSampleActivity",
                    "IO Exception in getFromLocation()", e1);
        } catch (IllegalArgumentException e2) {
            String errorString = "Illegal arguments " +
                    Double.toString(loc.getLatitude()) +
                    " , " +
                    Double.toString(loc.getLongitude()) +
                    " passed to address service";
            Log.e("LocationSampleActivity", errorString, e2);
        }
	
		if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String addressText = String.format(
                    "%s, %s",
                    address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
                    address.getLocality());
            Log.d(SolidalApp.TAG, "Reverse address: "+addressText);
            return addressText;
       }

       return "";
	}
	
	@Override
	protected void onPostExecute(String result) {
		if(result!=null && !"".equals(result) && context.getApp()!=null)
			context.getApp().setData(DataKey.ADDRESS_TEXT, result);
	}
	
}
